/**
 * Created by smp on 2017/4/14.
 */
var modelPath=ROOT_PATH+'/observation/observationCardMonthReport/';
var disposeData;
var unitTreeName;
var lastEditRowIndex;
if ($("#auth").val() == "no") {
    afterTreeLoadSuccess();
}
function deleteMessage(param) {
    var ind=layer.confirm('是否确定删除？', {
        btn: ['确定','取消'] //按钮
    },function(){
        layer.close(ind);
        var row = $('#tg2').datagrid('getSelected');
        if (row) {
            var rowIndex = $('#tg2').datagrid('getRowIndex', row);
            $('#tg2').datagrid('deleteRow', rowIndex);
        }
    })
}
/**
 * 编辑当前行
 * @param id
 */
function editRowByRowIndex() {
    var selectRow=$('#tg2').datagrid('getSelected');
    if (selectRow) {
        var selectRowIndex = $('#tg2').datagrid('getRowIndex', selectRow);
        $('#tg2').datagrid('beginEdit', selectRowIndex);
        lastEditRowIndex=selectRowIndex;
    }
}
/**
 * 结束编辑当前行
 * @param id
 */
function endRowByRowIndex() {
    var selectRow=$('#tg2').datagrid('getSelected');
    var selectRowIndex=$('#tg2').datagrid('getRowIndex',selectRow);
    $('#tg2').datagrid('endEdit',selectRowIndex);
}
var newMonth=$(":input[name=obsMonth]").val();
if(newMonth<10){
    newMonth='0'+newMonth;
}
var param1=null,param2=$(":input[name=obsYear]").val(),param3=newMonth,paramText=null;
//初始化下拉树
$('.parentDepartmentId').combotree({
    url: ROOT_PATH+'/permission/department/getDepartmentTree.shtml?parentId=0',
    required: true,
    onLoadSuccess:function (node,data) {
        param1=$('.parentDepartmentId').combotree("getValue");
        paramText=$('.parentDepartmentId').combotree("getText");
        disposeData=data;
        afterTreeLoadSuccess();
    },
    onChange:function (newValue,oldValue) {
        param1=newValue;
        paramText=$('.parentDepartmentId').combotree("getText");
        if(!(param1==null||param2==null||param3==null)){
            report_table(param1,param2,param3,paramText);
        }

    }
});
function afterTreeLoadSuccess() {
    $('#tg2').datagrid({
        method: 'post',
        url: modelPath + 'monthRepData.shtml',
        queryParams: {
            reportId: $(":input[name=id]").val()
        },
        //idField: 'id',
        fitColumns: true,
        pagination: false,
        //rownumbers: true,
        sortOrder: true,
        striped: true,
        singleSelect: true,
        fit: true,
        columns: [[
            {field: 'id', width: 150, title: '操作',
                formatter: function (value, row, index) {
                    if ($("#auth").val() == "yes") {
                        return "<input type='button' style='color: blue;width: 24px' onclick='deleteMessage(this)' value='删除'/>&nbsp;<input type='button' style='color: blue;width: 24px' onclick='editRowByRowIndex(this)' value='编辑'/>&nbsp;<input type='button' style='color: blue;width: 48px' onclick='endRowByRowIndex(this)' value='结束编辑'/>";
                    } else {
                        return '';
                    }
                }},
            {field: 'deptId', title: '部门单位名称', width: 280,
                editor: {
                    type: 'combotree',
                    options: {
                        required: true,
                        valueField: 'id',
                        textField: 'name',
                        data: disposeData,
                        panelHeight: "auto",
                        onSelect: function (record) {
                            var edUnitId = $("#tg2").datagrid('getEditor', {
                                index: lastEditRowIndex,
                                field: 'deptId'
                            });
                            $(edUnitId.target).val(record.id);
                            //为 unitTreeName赋值
                            unitTreeName = record.text;

                        }
                    }
                },
                formatter: function (value, row, index) {
                    if (unitTreeName == null || unitTreeName == '') {
                        return row.deptName;
                    } else {
                        return unitTreeName;
                    }
                }
            },
            {field: 'allCount', title: '合计', width: 80},
            {field: 'actCount', title: '不安全行为', width: 100,
                editor: {
                    type: 'textbox',
                    options: {
                        required: true
                    }
                }},
            {field: 'stateCount', title: '不安全状态', width: 100, editor: {
                type: 'textbox',
                options: {
                    required: true
                }
            }},
            {field: 'safeActCount', title: '推荐安全行为', width: 100, editor: {
                type: 'textbox',
                options: {
                    required: true
                }
            }}
        ]]
    });
}

var report_table=function (dept,year,month,deptParamName) {
    unitTreeName=null;
    var obsNums=0,obsUnSafeNums=0,obsProblemNums=0;
    $('#tg2').datagrid({
        method: 'post',
        url: modelPath + 'dataList.shtml',
        queryParams: {
            deptId:dept,
            year:year,
            month:month
        },
        //idField: 'id',
        fitColumns: true,
        pagination: false,
        //rownumbers: true,
        sortOrder: true,
        striped: true,
        singleSelect:true,
        fit: true,
        columns: [[
            {field: '操作',width: 150,title: '操作', formatter: function(value, row, index){
                return "<input type='button' style='color: blue;width: 24px' onclick='deleteMessage(this)' value='删除'/>&nbsp;<input type='button' style='color: blue;width: 24px' onclick='editRowByRowIndex(this)' value='编辑'/>&nbsp;<input type='button' style='color: blue;width: 48px' onclick='endRowByRowIndex(this)' value='结束编辑'/>"  ;
            }},
            {field: 'deptId', title: '部门单位名称', width: 280,
                editor:{
                type:'combotree',
                options:{
                    required:true,
                    valueField : 'id',
                    textField : 'name',
                    data : disposeData,
                    panelHeight:"auto",
                    onSelect : function(record){
                        var edUnitId = $("#tg2").datagrid('getEditor',{
                            index : lastEditRowIndex,
                            field : 'deptId'
                        });
                        $(edUnitId.target).val(record.id);
                        //为 unitTreeName赋值
                        unitTreeName = record.text;

                    }
                }},
                formatter : function(value,row,index){
                    if(unitTreeName==null||unitTreeName==''){
                        return row.deptName;
                    }else{
                        return unitTreeName;
                    }
                }},
            {field: 'allCount', title: '合计', width: 80},
            {field: 'actCount', title: '不安全行为', width: 100,
                editor:{
                type:'textbox',
                options: {
                    required: true
                }
            }},
            {field: 'stateCount', title: '不安全状态', width: 100,
                editor:{
                type:'textbox',
                options: {
                    required: true
                }
            }},
            {field: 'safeActCount', title: '推荐安全行为', width: 100,
                editor:{
                type:'textbox',
                options: {
                    required: true
                }
            }}
        ]],
        onLoadSuccess:function (data) {
           /* for(var i=0;i<data.rows.length;i++){
                obsNums+=data.rows[i].obsNums;
                obsUnSafeNums+=data.rows[i].obsUnSafeNums;
                obsProblemNums+=data.rows[i].obsProblemNums;
            }*/
            obsNums+=data.rows[data.rows.length-1].obsNums;
            obsUnSafeNums+=data.rows[data.rows.length-1].obsUnSafeNums;
            obsProblemNums+=data.rows[data.rows.length-1].obsProblemNums;
            $("#obsNum").text(obsNums);
            $("#obsUnSafeNum").text(obsUnSafeNums);
            $("#obsProblemNum").text(obsProblemNums);
            $(":input[name=peopleObsNum]").val(obsNums);
            $(":input[name=actNum]").val(obsUnSafeNums);
            $(":input[name=unsafeNum]").val(obsProblemNums);
            $("#obsName").textbox('setValue', deptParamName+year+month+"观察月报");
        }
    });
};
$(":input[name=obsYear]").combobox({
    onChange:function (newValue,oldValue) {
        param2=newValue;
        if(!(param1==null||param2==null||param3==null))
            report_table(param1,param2,param3,paramText);
    }
});
$(":input[name=obsMonth]").combobox({
    onChange:function (newValue,oldValue) {
        if(newValue<10){
            param3='0'+newValue;
        }else{
            param3=newValue;
        }
        if(!(param1==null||param2==null||param3==null))
            report_table(param1,param2,param3,paramText);
    }
});

$("#cardReportSave").on("click",function(){
    var index=layer.confirm('是否确定保存？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        if( $("#obsAllDos").textbox("getValue")==null|| $("#obsAllDos").textbox("getValue")==''){
            layer.close(index);
            layer.msg('请填写情况描述', {
                icon: 2,
                time: 2000
            });
            return;
        }
        if( $("#obsAnsRes").textbox("getValue")==null|| $("#obsAnsRes").textbox("getValue")==''){
            layer.close(index);
            layer.msg('请填写分析结论', {
                icon: 2,
                time: 2000
            });
            return;
        }
        if( $("#obsAdv").textbox("getValue")==null|| $("#obsAdv").textbox("getValue")==''){
            layer.close(index);
            layer.msg('请填写建议措施和实际改进情况', {
                icon: 2,
                time: 2000
            });
            return;
        }
        $.ajax({
            type: "POST",
            url: modelPath+'judgement.shtml',
            data: {obsName:$("#obsName").val(),id:$(":input[name=id]").val()},
            dataType: "json",
            success: function(result){
                if (result.success) {
        var data = $('#tg2').datagrid('getData');
        var json=JSON.stringify(data.rows);
        $('#cardForm').form('submit', {
            url: modelPath+'edit.shtml',
            //queryParams:{monthRepDataList:json},
            onSubmit: function (param) {
                param.monthRepDataList=json;
                var isValid = $(this).form('validate');
                if (!isValid) {
                    layer.close(index);
                    layer.msg("请正确填写表单")
                }
                return $(this).form('validate');
            },
            success: function (result) {
                result = $.parseJSON(result);
                if (result.success){
                    //$.messager.progress('close');	// 如果提交成功则隐藏进度条
                    parent.layer.msg(result.message,{time:1000,icon:1},function () {
                        parent.$('#dg1').datagrid('load');
                        parent.layer.closeAll(); //先得到当前iframe层的索引
                    });
                }else {
                    //$.messager.progress('close');	// 如果提交成功则隐藏进度条
                    parent.layer.msg(result.message,{time:1000,icon:2});
                }
            }
        });
                }
                else {
                    layer.msg('报表名称重复', {
                        icon: 2,
                        time: 2000
                    });
                }
            }
        });
    });
});
